package com.casa.POI.dianping;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.htmlcleaner.TagNode;
import org.htmlcleaner.XPatherException;



public class FetchSearchUrlsExecutor extends CityExecutor {
	
	public FetchSearchUrlsExecutor(int cityId) {
		super(cityId);
	}

	private List<String> finalUrls = new ArrayList<String>();

	@Override
	public void execute() {
		try {
			buildSearchUrls();
			persistSearchUrls();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XPatherException e) {
			e.printStackTrace();
		}
	}

	private void persistSearchUrls() {
		Session s = SessionManager.getInstance().openSession();
		s.beginTransaction();
		for (String url : finalUrls) {
			SearchUrl searchUrl = new SearchUrl(url, getCityId());
			if (s.get(SearchUrl.class, url) == null) {
				s.save(searchUrl);
				printStatus("add "+ url);
			}
		}
		s.getTransaction().commit();
		s.close();
	}

	private void buildSearchUrls() throws IOException, XPatherException {
		String shopAllUrl = String.format("/shopall/%d/0", getCityId());
		
		TagNode node = null;
		while (node == null) {
			try {
				node = SpiderUtil.cleanUrl(shopAllUrl);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		ArrayList<String> categoryUrls = new ArrayList<String>();
		ArrayList<String> regionUrls = new ArrayList<String>();
		
		Object[] values = node.evaluateXPath("//div[@class='box shopallCate']");
		Object[] categoriesLv1 = ((TagNode) values[0]).evaluateXPath("//dl[@class='list']");
		for (Object nodeLv1 : categoriesLv1) {
			Object[] categoriesLv2 = ((TagNode) nodeLv1).evaluateXPath("//a[@class='B']");
			for (Object nodeLv2 : categoriesLv2) {
				categoryUrls.add(((TagNode) nodeLv2).getAttributeByName("href"));
			}
		}
		
		if (values.length == 1) {
			finalUrls.addAll(categoryUrls);
		} else {
			Object[] regionsLv1 = ((TagNode) values[1]).evaluateXPath("//dl[@class='list']");
			for (Object nodeLv1 : regionsLv1) {
				TagNode regionLv1 = (TagNode) ((TagNode) nodeLv1).evaluateXPath("//a[@class='Bravia']")[0];
				regionUrls.add(regionLv1.getAttributeByName("href"));
				Object[] regionsLv2 = ((TagNode) nodeLv1).evaluateXPath("//a[@class='B']");
				for (Object nodeLv2 : regionsLv2) {
					TagNode regionLv2 = (TagNode) nodeLv2;
					regionUrls.add(regionLv2.getAttributeByName("href"));
				}
			}
			
			for (String categoryUrl : categoryUrls) {
				for (String regionUrl : regionUrls) {
					String finalUrl = categoryUrl + regionUrl.substring(regionUrl.lastIndexOf('r'));
					finalUrls.add(finalUrl);
				}
			}
		}
	}

}
